package cn.edu.tjufe.llp.tin.repository;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.NoRepositoryBean;

@NoRepositoryBean
public interface SoftDeletesRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
	@Query("select e from #{#entityName} e where e.deleted = 0")
	List<T> findAllActive();

	@Query("select e from #{#entityName} e where e.id in ?1 and e.deleted = 0")
	List<T> findAllActive(Iterable<ID> ids);

	@Query("select e from #{#entityName} e where e.id = ?1 and e.deleted = 0")
	Optional<T> findByIdActive(ID id);

	// Look up deleted entities
	@Query("select e from #{#entityName} e where e.deleted != 0")
	List<T> findAllInactive();

	@Query("select count(e) from #{#entityName} e where e.deleted = 0")
	long countActive();

	default boolean existsActive(ID id) {
		return findByIdActive(id).isPresent();
	}

	@Query("update #{#entityName} e set e.deleted = ?1 where e.id = ?1")
	@Modifying
	int softDelete(Long id);

	// 写这两个函数，需要将类名上的泛型改成<T extends BaseEntity, ID extends Serializable>
//	default void delete(T entity) {
//		delete(entity.getId());
//	}
//
//	default void delete(Iterable<? extends T> entities) {
//		entities.forEach(entitiy -> delete(entitiy.getId()));
//	}

	@Query("update #{#entityName} e set e.deleted = e.id where e.id in ?1")
	@Modifying
	int softDelete(Iterable<ID> ids);
}
